import { Table, Modal, message, Space, Tabs } from 'antd'
import React, { useRef, useState, useEffect } from 'react'
import { EditableProTable, ProColumns, ActionType } from '@ant-design/pro-table'
import type { ProFormInstance } from '@ant-design/pro-form'
import { useT, request } from '@designable/event-system'
import { FormCascaderCategory } from '../FormCascaderCategory'

// 核销商品列表
function qrProductList(params: any) {
  return request({
    uri: `/api/tenant/qr/v2/product/page`,
    params,
    method: 'POST',
  })
}

// 预约商品列表
function reservationProductPage(params: any) {
  return request({
    uri: '/api/tenant/reservation/product/page',
    params,
    method: 'POST',
  })
}

// 会籍商品列表
function membershipProductPage(params: any) {
  return request({
    uri: '/api/tenant/ms/product/page',
    params,
    method: 'POST',
  })
}

type SelectModalProps = {
  customerCode: string
  agreementCode: string
  productList: any
  visible: boolean
  onCancel: () => void
  onOk: (a: any) => any
}

export default function SelectModal(props: SelectModalProps) {
  const { visible, onCancel, onOk, customerCode, agreementCode } = props
  let productList = Array.isArray(props.productList) ? props.productList : []
  const actionRef = useRef<ActionType>()
  const selectedProCodes = (productList || []).map((item: any) => item.proCode)
  const [selectData, setSelectData] = useState<any>([])
  const keys = selectData.map((item: any) => item.proCode)
  const [goodsType, setGoodsType] = useState<any>('1')
  const $t = useT()

  const columns: ProColumns[] = [
    {
      width: 200,
      title: '商品编号',
      dataIndex: 'proCode',
      search: false,
      ellipsis: true,
    },
    {
      title: '商品名称',
      dataIndex: 'proName',
      ellipsis: true,
    },
    {
      width: 200,
      title: '品类类型',
      dataIndex: 'categoryType',
      ellipsis: true,
      valueType: 'select',
      renderFormItem: () => {
        return <FormCascaderCategory />
      },
      render: (text, record, _, action) => {
        return record.subTypeName
          ? `${record.categoryTypeName} / ${record.subTypeName}`
          : record.categoryTypeName
      },
    },
    {
      width: 150,
      title: '可售库存',
      dataIndex: 'stockNum',
      search: false,
      render: (text, record) => {
        const { stockLimit, availableStockNum } = record
        return stockLimit ? availableStockNum : '不限制'
      },
    },
    {
      width: 150,
      title: '状态',
      dataIndex: 'proStatusName',
      ellipsis: true,
      search: false,
    },
  ]

  useEffect(() => {
    actionRef.current?.reloadAndRest()
  }, [goodsType])
  useEffect(() => {
    !visible && setSelectData([])
  }, [visible])

  return (
    <div>
      <Modal
        title={$t('选择商品')}
        width={1200}
        open={visible}
        destroyOnClose={true}
        onOk={async () => {
          if (selectData.length === 0) {
            message.error($t('请选择商品'))
            return
          }
          onOk(
            [...productList, ...selectData].reduce((acc, current) => {
              const x = acc.find(
                (item: any) => item.proCode === current.proCode
              )
              if (!x) {
                return acc.concat(current)
              } else {
                return acc
              }
            }, [])
          )
        }}
        onCancel={() => {
          setSelectData([])
          onCancel()
        }}
      >
        <EditableProTable
          columns={columns}
          actionRef={actionRef}
          recordCreatorProps={false}
          rowSelection={{
            selectedRowKeys: [...keys, ...selectedProCodes],
            onSelect: (record, selected) => {
              if (selected) {
                setSelectData([...selectData, record])
              } else {
                setSelectData(
                  selectData.filter(
                    (item: any) => item.proCode !== record.proCode
                  )
                )
              }
            },
            getCheckboxProps: (record) => {
              const disabled = selectedProCodes.includes(record.proCode)
              return {
                disabled,
              }
            },
          }}
          request={async ({ pageSize = 10, ...params }) => {
            let res: any = {}
            if (goodsType === '1') {
              res = await qrProductList({
                size: pageSize,
                ...params,
                proStatus: 2,
                customerCode,
                agreementCode,
                sortRule: 'updateTime',
              })
            } else if (goodsType === '2') {
              res = await reservationProductPage({
                size: pageSize,
                ...params,
                proStatus: 2,
                customerCode,
                agreementCode,
                sortRule: 'updateTime',
              })
            } else if (goodsType === '3') {
              res = await membershipProductPage({
                size: pageSize,
                ...params,
                proStatus: 2,
                customerCode,
                sortRule: 'updateTime',
              })
            }
            const { records, total } = res as any
            return {
              data: records,
              success: true,
              total: total,
            }
          }}
          rowKey="proCode"
          search={{
            labelWidth: 'auto',
            collapsed: false,
            collapseRender: () => <></>,
            style: {
              background: '#F7F8FA',
              padding: '24px 20px',
              borderRadius: 4,
            },
          }}
          pagination={{
            size: 'default',
            defaultPageSize: 10,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50', '100'],
          }}
          dateFormatter="string"
          toolBarRender={() => [
            <div className="tool-bar-render" key="tool">
              <Tabs
                type="card"
                onChange={(e: any) => {
                  setGoodsType(e)
                }}
                activeKey={goodsType}
                items={[
                  { key: '1', label: '核销商品' },
                  { key: '2', label: '预约商品' },
                  { key: '3', label: '会籍商品' },
                ]}
                tabBarStyle={{
                  width: 890,
                }}
              ></Tabs>
            </div>,
          ]}
        />
      </Modal>
    </div>
  )
}
